<template>
    <div class="clearFix operating">
        <div class="bg-box"></div>
        <div class="main">
          <!-- 钱包余额 -->
          <div class="balance-warp">
            <div class="item icon-box clearfix">
              <i class="icon-qianbao"></i>
            </div>
            <div class="item balance">
              <p class="number">
                {{ moneybag }}
              </p>
              <p>钱包余额</p>
            </div>
            <div class="withdraw item">
              <a @click="withdrawHandle" href="javascript:;"  v-if="+moneybag > 100"> 提 现 </a>
            </div>
          </div>
          <!-- 今日收入 -->
          <div class="today-income">
            <p class="title">今日收入 （元）</p>
            <p class="cash">{{income}}</p>
          </div>
          <!-- 当* 统计 -->
          <div class="order-count">
            <div class="dimension-time boxShadow">
              <div class="tab-wrap">
                <div @click="toggleBar('day')" class="item" :class="{'isActive': active === 'day'}">当日订单</div>
                <div @click="toggleBar('month')" class="item" :class="{'isActive': active === 'month'}">当月订单</div>
                <div @click="toggleBar('year')" class="item" :class="{'isActive': active === 'year'}">当年订单</div>
              </div>
              <div class="content">
                <div class="label">
                  <p>洗衣机</p>
                  <p>烘干机</p>
                </div>
                <div class="grid">
                  <div class="item xy">
                    <div :style="{ width: width + '%' }" class="deviceX"><span style="padding-right: 0px"> {{ xyjCount }} </span> </div>
                  </div>
                  <div class="item hg" v-if="hgjCount === 0 && xyjCount === 0">
                    <div style="width:0" class="deviceH"><span > {{ hgjCount }} </span> </div>
                  </div>
                  <div class="item hg" v-else>
                    <div :style="{ width: (100 - width) + '%' }" class="deviceH"><span > {{ hgjCount }} </span> </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- 折线统计 -->
          <div class="line-box boxShadow">
            <div class="date-filter">
              <div class="item">
                <span class="label">年份</span>
                <span class="input" @click="queryYear">
                  <i class="icon-time"></i>
                  <span>{{year}}</span>年
                </span>
              </div>
              <div class="item">
                <span class="label">月份</span>
                <span class="input" @click="queryMonth">
                  <i class="icon-time"></i>
                  <span>{{month}}</span>月
                </span>
              </div>
            </div>
            <div class="line-warp">
              <div class="color-4c title">收入（X轴日期：号，Y轴单位：元）</div>
              <div class="legend">
                <div class="item">
                  <i class="icon-XYJ-Kg"></i>
                  洗衣机
                </div>
                <div class="item">
                  <i style="display: inline-block" class="icon-HGJ-kg"></i>
                  烘干机
                </div>
              </div>
              <div ref="line" class="line"></div>
            </div>
          </div>
        </div>
        <QPup title="请选择提现方式" class="withdraw-type" v-model="dialogStatusCood">
          <div class="box">
            <div  @click="toggleType('wx')" :class="{'withdraw': withdraw === 'wx'}"  class="item wx">
              <i class="iconfont icon">&#xe603;</i>
              <span class="pic-box">
              </span>
            </div>
            <div  @click="toggleType('zyb')" :class="{'withdraw': withdraw === 'zyb'}" class="item zfb">
              <i class="iconfont icon">&#xe603;</i>
              <span></span>
            </div>
            <div  @click="toggleType('yhk')" :class="{'withdraw': withdraw === 'yhk'}" class="item yhk">
              <i class="iconfont icon">&#xe603;</i>
              <span></span>
            </div>
          </div>
          <a class="btn" @click="toCash" href="javascript:;">确认 </a>
        </QPup>
    </div>
</template>
<script>
  import Echarts from 'echarts'
  import getYear from 'utils/getYear';
  import QPup from '@/components/q_pup.vue';
  import * as api from 'api';
  import { mapState } from 'vuex'
  function getLineOption (arr) {
    return {
      color: ['#4282f9', '#ff8049'],
      backgroundColor: '#f6fbff',
      tooltip: {
        trigger: 'axis'
      //  formatter: '{a} : {c}'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: arr[0],
        axisLine: {
          show: false
        },
        axisLabel: {
          show: true,
          margin: 10,
          textStyle: {
            color: '#979a9a',
            width: '500px'
          }
        },
        axisTick: {
          show: false
        }
      },
      dataZoom: {
        show: true,
        realtime: true,
        start: 0,
        end: 100
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false
        },
        axisLabel: {
          show: true,
          margin: 10,
          textStyle: {
            color: '#979a9a'
          }
        },
        axisTick: {
          show: false
        }
      },
      series: [{
        name: '洗衣机',
        type: 'line',
        stack: '洗衣机',
        data: arr[1]
      }, {
        name: '烘干机',
        type: 'line',
        stack: '烘干机',
        data: arr[2]
      }]
    };
  }
  let years = [];
  getYear(2010).forEach(item => {
    years.push({ label: item, value: item })
  });
  let months = [
    { label: 1, value: 1 },
    { label: 2, value: 2 },
    { label: 3, value: 3 },
    { label: 4, value: 4 },
    { label: 5, value: 5 },
    { label: 6, value: 6 },
    { label: 7, value: 7 },
    { label: 8, value: 8 },
    { label: 9, value: 9 },
    { label: 10, value: 10 },
    { label: 11, value: 11 },
    { label: 12, value: 12 }
  ];
  let arr = []
  export default {
    data() {
      return {
        active: 'day',
        xyjCount: 0,
        hgjCount: 0,
        year: new Date().getFullYear(),
        month: new Date().getMonth() + 1,
        income: 0,
        dialogStatusCood: false,
        withdraw: 'wx',
        line: {
          xAxisData: [],  // 折线横坐标
          yAxisDataX: [], // 洗衣机y轴数据
          yAxisDataH: []  // 烘干机y轴数据
        }
      }
    },

    components: {
      QPup
    },

    computed: {
      ...mapState({
        moneybag: state => state.userInfo.operatingAmount
      }),
      width() {
        if (this.xyjCount !== 0) {
          return (this.xyjCount / (this.xyjCount + this.hgjCount)) * 100
        }
        return this.xyjCount
      }
    },

    methods: {
      // 当日收入
      queryIncome () {
        api.queryIncome({
          agencyId: this.$store.state.userInfo.id
        })
          .then(res => {
            this.income = res.resultData - 0
          })
      },

      // 统计单位查询
      queryTj() {
        this.xyjCount = 0;
        this.hgjCount = 0;
        api.queryStatistics({
          agencyId: this.$store.state.userInfo.id,
          unitType: this.active === 'day'
            ? 0 : this.active === 'month'
              ? 1 : this.active === 'year' ? 2 : -1
        })
          .then(res => {
            if (res.resultData === '') {
              this.xyjCount = 0;
              this.hgjCount = 0;
              return
            }
            res.resultData.forEach((item, index) => {
              if (item.deviceType === '1') {
                this.xyjCount = +item.orderCount
              }
              if (item.deviceType === '2') {
                this.hgjCount = +item.orderCount
              }
            })
          })
      },
      // 获取每月的天数
      lineX () {
        if (this.month === (new Date().getMonth() + 1)) {
          let day = (new Date()).getDate()
          for (let i = 1; i <= day; i++) {
            this.line.xAxisData.push(i)
          }
        } else {
          let day = (new Date(this.year, this.month, 0)).getDate();
          for (let i = 1; i <= day; i++) {
            this.line.xAxisData.push(i)
          }
        }
      },
      // 统计月查询  ---   折线图
      queryTime () {
        this.line.xAxisData = [];
        this.line.yAxisDataX = [];
        this.line.yAxisDataH = [];
        let that = this;
        api.queryByMonth({
          agencyId: this.$store.state.userInfo.id,
          year: this.year,
          month: this.month
        })
          .then(res => {
            res.resultData.forEach((item, key) => {
              item.deviceType_1 ? that.line.yAxisDataX.push(+item.deviceType_1) : that.line.yAxisDataX.push(0);
              item.deviceType_2 ? that.line.yAxisDataH.push(+item.deviceType_2) : that.line.yAxisDataH.push(0);
              that.line.xAxisData.push(new Date(item.orderDate).getDate())
            });
            if (res.resultData.length > 0) {
              arr = [that.line.xAxisData, that.line.yAxisDataX, that.line.yAxisDataH]
            } else {
              let day = (new Date(this.year, this.month, 0)).getDate()
              for (let i = 1; i <= day; i++) { // 添加横坐标天数（数据）
                that.line.xAxisData.push(i);
                this.line.yAxisDataX.push(0);
                this.line.yAxisDataH.push(0);
              }
              arr = [that.line.xAxisData, this.line.yAxisDataX, this.line.yAxisDataH]
            }
            // 获取chart的容器
            let lineBox = Echarts.init(this.$refs.line);
            lineBox.setOption(getLineOption(arr));
          })
      },

      toggleBar(type) {
        this.active = type;
        this.queryTj()
      },

      queryYear() {
        const that = this;
        weui.picker(years, {
          className: 'custom-classname',
          container: 'body',
          defaultValue: [new Date().getFullYear()],
          onChange: function (result) {
          },
          onConfirm: function (result) {
            that.year = result[0].value
            that.queryTime()
          },
          id: 'datePicker'
        });
      },

      queryMonth() {
        const that = this;
        weui.picker(months, {
          className: 'custom-classname',
          container: 'body',
          defaultValue: [new Date().getMonth() + 1],
          onChange: function (result) {
          },
          onConfirm: function (result) {
            console.log(result[0].value);
            that.month = result[0].value
            that.queryTime()
          },
          id: 'singleLinePicker'
        });
      },

      withdrawHandle() {
        api.priviledge({
          agencyId: this.$store.state.userInfo.id
        })
          .then(res => {
            if (+res.resultData === 1) {
              this.dialogStatusCood = !this.dialogStatusCood;
              return
            }
            if (+res.resultData === 0) {
              this.Toast('上次提现未超过3天，咱不支持提现');
              return
            }
            this.Toast('数据错误!');
          })
      },

      toggleType(type) {
        this.withdraw = type;
      },

      toCash() {
        this.$router.push({ path: '/cash/' + this.withdraw })
      }
    },

    created () {
      this.queryTj();
      this.queryTime();
      this.queryIncome();
      this.$store.dispatch('updateAmount')
    },

    mounted() {
      this.title('我的运营');
    }
  }
</script>

<style lang="scss" scoped="">
  @import '../../../styles/agent/operating/index';

  .withdraw-type {
    .box {
      background-color: #f7f9fa;
      padding: px2rem(20);
      div.item {
        margin-bottom: px2rem(12);
        background-color: #fff;
        @include hl(px2rem(120));
        padding-left: px2rem(44);
        box-shadow: 1px 1px 1px #f2f6f7, -1px -1px 1px #f2f6f7;
        i {
          color: #d7d7d7;
        }
        &.withdraw {
          i {
            color: #319cff;
          }
        }
        &.wx {
          position: relative;
          span {
            display: inline-block;
            width: px2rem(188);
            height: px2rem(65);
            @include bis('../../../imgs/wx@2x.png');
            @include ct();
            margin-left: px2rem(30);
          }
        }
        &.zfb {
          position: relative;
          span {
            display: inline-block;
            width: px2rem(186);
            height: px2rem(63);
            @include bis('../../../imgs/zfb@2x.png');
            @include ct();
            margin-left: px2rem(30);
          }
        }
        &.yhk {
          position: relative;
          span {
            display: inline-block;
            width: px2rem(203);
            height: px2rem(46);
            @include bis('../../../imgs/yhk@2x.png');
            @include ct();
            margin-left: px2rem(30);
          }
        }
      }
    }
    a.btn {
      display: inline-block;
      width: 100%;
      text-align: center;
      @include hl(px2rem(100));
      @include sc(px2rem(32), #FFF);
      background-color: #2f99fc;
    }
  }

</style>
